package com.edais.service.imp.gift;

import com.edais.domain.User;
import com.edais.domain.gift.*;
import com.edais.service.GiftExchangeFunction;
import com.edais.service.UserService;
import com.edais.service.gift.GiftPackageGiftOrderService;
import com.edais.service.gift.PointAccountService;
import com.edais.service.gift.PointFlowService;
import com.edais.service.gift.PointOrderService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 积分
 * Created by haoyx on 2016/11/10.
 */
@Service("pointImpl")
public class PointImpl implements GiftExchangeFunction {

    private static final Logger logger = Logger.getLogger(PointImpl.class);

    @Autowired
    private UserService userService;

    @Autowired
    private PointAccountService accountService;

    @Autowired
    private PointOrderService pointOrderService;

    @Autowired
    private PointFlowService pointFlowService;

    @Autowired
    private GiftPackageGiftOrderService orderService;

    @Override
    @Transactional(propagation= Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
    public Map<String,String> apply(Map<String,Object> params) throws Exception {

        Map<String, String> resMap = new HashMap<String, String>();
        String error = validParams(params);
        if(!StringUtils.isEmpty(error)){
            logger.info(error);
            error = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
                    Consts.ErrorMsg.MSG00001,error);
            resMap.put("error",error);
            return resMap;
        }

        //参数获取
        GiftPackageGift giftPackageGift = (GiftPackageGift)params.get("giftPackageGift");
        Long packageOrderId = Long.valueOf(params.get("packageOrderId").toString());
        String userId = params.get("userId").toString();
        String mobile = String.valueOf(params.get("mobile"));
        Integer amount = Integer.valueOf(params.get("amount").toString());
        String period = params.get("period").toString();

        final String logInfo = "积分" + giftPackageGift.getId() + userId + "-";

        logger.info(logInfo+"开始");

        User user = this.userService.selectUser(Long.valueOf(userId),mobile);
        if(null == user){
            logger.info(logInfo+"查询不到此用户");
            error = CommonUtil.setResultStringCn(new HashMap<String, Object>(),Consts.ERROR_CODE,
                    Consts.ErrorMsg.MSG00001,"查询不到此用户");
            resMap.put("error",error);
            return resMap;
        }


        Date nowDate = userService.getSysdate();

        //生成订单
        GiftPackageGiftOrder order = this.orderService.generateOrder(logInfo,packageOrderId,user,giftPackageGift,nowDate);

        this.addAccountAmount(logInfo,order,user,nowDate,amount,period);

        logger.info(logInfo+"成功");

        return resMap;
    }

    @Override
    public String validParams(Map params) {
        if(null == params || params.isEmpty())
            return "参数列表不能为空";
        if(!params.containsKey("giftPackageGift") || null == params.get("giftPackageGift"))
            return "参数giftPackageGift不能为空";
        if(!params.containsKey("packageOrderId")  || StringUtils.isEmpty(params.get("packageOrderId")))
            return "参数packageOrderId不能为空";
        if(!params.containsKey("userId")  || StringUtils.isEmpty(params.get("userId")))
            return "参数userId不能为空";
        if(!params.containsKey("mobile")  || StringUtils.isEmpty(params.get("mobile")))
            return "参数mobile不能为空";
        if(!params.containsKey("amount")  || StringUtils.isEmpty(params.get("amount")))
            return "参数amount不能为空";
        if(!params.containsKey("period")  || StringUtils.isEmpty(params.get("period")))
            return "参数period不能为空";
        return null;
    }

    private void addAccountAmount(String logInfo,GiftPackageGiftOrder order, User user,Date nowDate,Integer amount,String period){
        logger.info(logInfo+"增加用户积分");
        //查找账户
        PointAccount account = this.accountService.findAccount(user);
        if(null == account){
            //如果积分账户不存在则需要新创建
            account = this.accountService.createAccount(logInfo, user, nowDate);
        }
        //增加账户总积分---所有操作前执行，锁定主账号，进行积分充值
        logger.info(logInfo+"增加账户总积分开始");

        if(0 >= amount){
            logger.info(logInfo+"增加账户总积分失败account-"+account+"amount-"+amount);
        }


        /**
         * 等级变更---采用异步，就算失败也不能影响其他业务逻辑
         * 插t_user_message表
         * 如果升级到可以自动签到的等级就进行签到，如果原等级就可以自动签到则不需要签到
         */
        accountService.pointUpgradeOpt(logInfo,user,account.getTotalAmount(),amount);

        this.accountService.addPointAmount(account,amount,nowDate);
        logger.info(logInfo+"增加账户总积分成功");

        //创建订单
        PointOrder pointOrder = pointOrderService.createPointOrder(logInfo, account, nowDate,
                period, amount);

        //创建流水
        PointFlow flow = new PointFlow(account,pointOrder,order);
        flow.setIntro("大礼包");
        this.pointFlowService.incomeFlow(logInfo, flow, amount);

    }
}
